<template>
  <el-dialog
    :model-value="visible"
    :title="title"
    width="600px"
    :before-close="handleClose"
    append-to-body
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      <el-form-item label="数据格式名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入数据格式名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="通信方向" prop="direction">
        <el-radio-group v-model="formData.direction">
          <el-radio :value="0">请求</el-radio>
          <el-radio :value="1">响应</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="请求方式" prop="requestType">
        <el-radio-group v-model="formData.requestType">
          <el-radio value="GET">GET</el-radio>
          <el-radio value="POST">POST</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="消息类型" prop="messageType">
        <el-radio-group v-model="formData.messageType">
          <el-radio value="get">get</el-radio>
          <el-radio value="set">set</el-radio>
          <el-radio value="report">report</el-radio>
          <el-radio value="heartbeat">heartbeat</el-radio>
          <el-radio value="register">register</el-radio>
          <el-radio value="alarm">alarm</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="数据格式类型" prop="dataformatType">
        <el-radio-group v-model="formData.dataformatType">
          <el-radio value="bytes">bytes</el-radio>
          <el-radio value="key-value">key-value</el-radio>
          <el-radio value="json">json</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="功能或方法名" prop="command">
        <el-input
          v-model="formData.command"
          placeholder="请输入功能或方法名"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="接口相对路径" prop="url">
        <el-input
          v-model="formData.url"
          placeholder="请输入接口相对路径"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="数据解析方式" prop="scriptType">
        <el-radio-group v-model="formData.scriptType">
          <el-radio value="">系统默认</el-radio>
          <el-radio value="Groovy">Groovy</el-radio>
          <el-radio value="JavaScript">JavaScript</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item v-if="formData.scriptType && formData.scriptType !== ''" label="代码脚本" prop="scriptContent">
        <el-input
          v-model="formData.scriptContent"
          type="textarea"
          :rows="6"
          placeholder="请输入代码脚本"
          maxlength="5000"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { DataFormatInfo } from '@/api/IOT/protocolManage/dataFormatManage/types'

// Props定义
interface Props {
  visible: boolean
  title?: string
  data?: DataFormatInfo
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  title: '新增数据格式',
  loading: false
})

// Emits定义
interface Emits {
  'update:visible': [value: boolean]
  'submit': [data: DataFormatInfo]
  'cancel': []
}

const emit = defineEmits<Emits>()

// 响应式数据
const formRef = ref<FormInstance>()
const formData = ref<DataFormatInfo>({
  dataformatId: '',
  name: '',
  direction: 0,
  requestType: '',
  messageType: '',
  dataformatType: '',
  command: '',
  url: '',
  scriptType: '',
  scriptContent: '',
  decodeType: 0,
  scriptId: '',
  protocolId: '',
  protocolVersionId: '',
  createTime: '',
  updateTime: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入数据格式名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  direction: [
    { required: true, message: '请选择通信方向', trigger: 'change' }
  ],
  requestType: [
    { required: true, message: '请选择请求方式', trigger: 'change' }
  ],
  messageType: [
    { required: true, message: '请选择消息类型', trigger: 'change' }
  ],
  dataformatType: [
    { required: true, message: '请选择数据格式类型', trigger: 'change' }
  ],
  command: [
    { required: true, message: '请输入功能或方法名', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入接口相对路径', trigger: 'blur' },
    { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const isEdit = computed(() => !!props.data?.dataFormatId)

// 处理表单数据
const processFormData = (data: DataFormatInfo) => {
  return {
    ...data,
    direction: Number(data.direction)
  }
}

// 工具函数 - 重置表单
const resetForm = () => {
  Object.assign(formData.value, {
    dataformatId: '',
    name: '',
    requestType: '',
    direction: 0,
    messageType: '',
    dataformatType: '',
    command: '',
    url: '',
    scriptType: '',
    scriptContent: '',
    decodeType: 0,
    scriptId: '',
    protocolId: '',
    protocolVersionId: '',
    createTime: '',
    updateTime: ''
  })
  formRef.value?.clearValidate()
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  console.log(props.data)
  if (newVal) {
    if (props.data.dataformatId) {
      // 编辑模式，填充数据
      const processedData = processFormData(props.data)
      Object.assign(formData.value, processedData)
    } else {
      // 新增模式，重置表单
      resetForm()
    }
  }
})

// 监听数据变化
watch(() => props.data, (newData) => {
  if (newData && props.visible) {
    const processedData = processFormData(newData)
    Object.assign(formData.value, processedData)
  }
}, { deep: true })

// 事件处理函数
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 根据scriptType设置decodeType
    const getDecodeType = (scriptType: string) => {
      if (!scriptType || scriptType === '') return 0 // 系统默认
      if (scriptType === 'Groovy') return 1 // Groovy脚本
      if (scriptType === 'JavaScript') return 2 // JavaScript脚本
      return 0 // 默认值
    }
    
    // 准备提交数据，包含decodeType字段
    const submitData = {
      ...formData.value,
      decodeType: getDecodeType(formData.value.scriptType || '')
    }
    
    emit('submit', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleCancel = () => {
  resetForm()
  emit('cancel')
  emit('update:visible', false)
}

const handleClose = () => {
  handleCancel()
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>